(function () {
  //购物车模板
  var sCartTemplate = '';
  var oShoppingCartList = document.getElementById("shoppingcarList");
  var oShoppingCartListTab = oShoppingCartList.getElementsByClassName("carTab")[0] ;
  var checkAll=document.getElementById("chec");
  var origPrice=document.getElementById("origPrice");
  var origsave=document.getElementById("origsave");
  var payMoneyTxt=document.querySelector("#payMoneyTxt");
    var oGoodsCategory = document.getElementById("goods_category");
    /**
     * 处理商品分类数据
     */
    var doGoodsCategory = function(){
        var goods=JSON.parse(window.sessionStorage.goods);
        var oGoodsCategoryTempt="";
        $.map(goods, function(key){

            oGoodsCategoryTempt +="<li><a href='list.html?classID="+key+"'><img src='./images/"+key+".png' width='50px'><p>"+goods[key]+"</p></a></li>"
        });
        oGoodsCategory.innerHTML=oGoodsCategoryTempt;
    };
    /*
     更新购物车
     */
    var updateCart = function(data){
        $.post(
            ucshop.updataCartAddress(),
            data,
            function(err,data){
                try {
                    var dataJson = JSON.parse(data);
                    if (dataJson== ucshop.CODE.success) {
                        alert('操作成功！');
                    } else {
                        alert('系统错误');
                    }
                } catch(e) {
                    console.log(e.errors);
                }
            }
        );
    };
  /**
   * 处理购物车
   */
  var doCart = function(d) {
    try {
      $.each(d, function (item) {
    var discount= item.discount=='0'?1:(parseFloat(item.discount).toFixed(1)/10);
          item.discountPrice=parseFloat(item.price*discount).toFixed(2);
          item.discountTotal=parseFloat(item.discountPrice*parseInt(item.number)).toFixed(2);
          item.total=parseFloat(item.price*parseInt(item.number)).toFixed(2);
        var sLi = $.compile(sCartTemplate, item);
          oShoppingCartListTab.innerHTML += sLi;
      });

        var checkAllsss=document.getElementById("chec");
        /*结算购物车*/
        function  countCar(){
            var chkboxs=document.querySelectorAll(".chkbox");
            var length=chkboxs.length;
            var totalAll=0,
                totalDisAll=0,
                count=0;
            for(var i=0;i<length;i++){
                if(chkboxs[i].checked){
                    count++;
                    var price=chkboxs[i].getAttribute("price");
                    var disPrice=chkboxs[i].getAttribute("discount_price");
                    var num=parseInt(chkboxs[i].getAttribute("amount"));
                    totalAll+=price*num;
                    totalDisAll+=disPrice*num;
                }
            }
            payMoneyTxt.innerHTML=parseFloat(totalDisAll).toFixed(2);
            origPrice.innerHTML=parseFloat(totalAll).toFixed(2);
            origsave.innerHTML=parseFloat(totalAll-totalDisAll).toFixed(2);
            if (count==length){
                checkAllsss.checked="checked";
            }else{
                checkAllsss.checked=false;
            }
        }
        $.addEvent(oShoppingCartListTab,"click",function (e) {
          e=e||window.event;
     if(e.target.className=="remove"){
         var del=confirm("确定移除吗？");
         if (del==true) {
             var goodsID=e.target.getAttribute('data-goodsID');
             updateCart({goodsID: goodsID, number:0,userID:localStorage.getItem("userID")});
             this.removeChild(e.target.parentNode.parentNode.parentNode);
             countCar();
         }
     }else if(e.target.parentNode.className=="optUp"){
         var inputs=e.target.parentNode.nextSibling.nextSibling;
         var inputBox=e.target.parentNode.parentNode.parentNode.firstElementChild.firstElementChild;
         var values=parseInt(inputs.value);
         var price=document.getElementById("price"+inputs.getAttribute("data-goodsID"));
         values--;
         values= values <1 ? 1: values;
         inputs.value=values;
         price.innerHTML=(parseFloat(inputs.getAttribute("dis-price")).toFixed(2)*values).toFixed(2);
         price.nextSibling.nextSibling.nextSibling.innerHTML=parseFloat(inputs.getAttribute("price")*values).toFixed(2);
         inputBox.setAttribute("amount",values);
         countCar();

     }else if(e.target.parentNode.className=="optDown"){
         var inputs=e.target.parentNode.previousSibling.previousSibling;
         var inputBox=e.target.parentNode.parentNode.parentNode.firstElementChild.firstElementChild;
         var values=parseInt(inputs.value);
         var price=document.getElementById("price"+inputs.getAttribute("data-goodsID"));
         values++;
         values= values >100 ? 100: values;
         inputs.value=values;
         price.innerHTML=parseFloat(inputs.getAttribute("dis-price")*values).toFixed(2);
         price.nextSibling.nextSibling.nextSibling.innerHTML=parseFloat(inputs.getAttribute("price")*values).toFixed(2);
         inputBox.setAttribute("amount",values);
         countCar();
     }else if(e.target.className=="chkbox"){
         countCar();
     }else if(e.target.id=="chec"){
         var chkboxs=document.querySelectorAll(".chkbox");
         var length=chkboxs.length;
         if(e.target.checked){
             for(var i=0;i<length;i++){
                 chkboxs[i].checked="checked";
             }
             countCar();
         }else{
             for(var i=0;i<length;i++){
                 chkboxs[i].checked=false;
             }
             payMoneyTxt.innerHTML='0.00';
             origPrice.innerHTML='0.00';
             origsave.innerHTML='0.00';
         }
     }else{
         return;
     }
        });
    } catch(e) {
      console.log(e.errors);
    }
  };
  /**
   * 获取购物车数据
   */
  var getCart = function(){
    $.loadTemplate('./template/cart_item.html', function(err, data){
      if (err) {
        console.log(err);
        return;
      }
      sCartTemplate = data;

        $.jsonp(
            ucshop.getCartAddress(),
            {'format':"jsonp",'callback':"doCart",userID:localStorage.getItem("userID")},
            'doCart',
            doCart
        )
    });
  };




  window.onload = function() {
    ucshop.checkLoginStatus();
    ucshop.toTop();
    ucshop.searchGoods();
    ucshop.slide_up();
    //商品分类
    doGoodsCategory();
    //获取购物车
    getCart();
  }
})();